import { useState } from 'react';
import { Button, Space, Form, Row, Col, Table, Select } from 'antd';
import { PAGINATION_CONFIG } from '@/constants';
import type { MyExport, QueryMyExportListParams } from './services';
import { MyExportStatus, queryMyExportList, MyExportType, doMyExport } from './services'
import { useRequest } from 'ahooks';
import type { ColumnsType } from 'antd/es/table/interface';
import dayjs from 'dayjs';
import { enum2options } from '@/utils/enum2options';

let debounceTimer: NodeJS.Timeout | null = null

const AppUserPage: React.FC = () => {
  const [searchForm] = Form.useForm<QueryMyExportListParams>()
  const [searchParams, setSearchParams] = useState<QueryMyExportListParams>({
    pageNum: 1, pageSize: 10, isRead: MyExportStatus.未读,
  })
  const list = useRequest(() => queryMyExportList(searchParams), {
    refreshDeps: [searchParams],
  })
  const _exp = useRequest(doMyExport, {manual: true})

  const onFinish = (formValues: any) => {
    setSearchParams({
      ...searchParams,
      isRead: formValues.isRead,
      pageNum: 1,
    })
  }

  const download = (record: MyExport) => {
    const _a = document.createElement('a')
    _a.style.display = 'none'
    _a.download = `${record.fileName}.xlsx`
    _a.href = record.url
    document.body.appendChild(_a)
    _a.click()
    document.body.removeChild(_a)
    _exp.runAsync({id: record.id}).then(() => list.refresh())
  }

  const downloadDebounce = (record: MyExport) => {
    if (debounceTimer) clearTimeout(debounceTimer)
    debounceTimer = setTimeout(() => {
      download(record)
    }, 200)
  }

  const columns: ColumnsType<MyExport> = [
    {
      title: '类型',
      dataIndex: 'type',
      render: val => val ? MyExportType[val] : '--',
    },
    {
      title: '文件标题',
      dataIndex: 'fileName',
      render: val => val || '--'
    },
    {
      title: '是否已读',
      dataIndex: 'isRead',
      render: val => MyExportStatus[val]
    },
    {
      title: '导出时间',
      dataIndex: 'modifyTime',
      render: val => dayjs(val).format('YYYY-MM-DD HH:mm:ss')
    },
    {
      title: '操作',
      key: 'id',
      render: (val, record) => {
        return <Space>
          <a onClick={() => downloadDebounce(record)}>下载</a>
        </Space>
      }
    },
  ]
  
  return (
    <div className='container'>
      <div className="card search-card">
        <div className="form-area">
          <Form name='searchCarTypeForm' form={searchForm} onFinish={onFinish} initialValues={{isRead: MyExportStatus.未读}}>
            <Row gutter={[20, 20]}>
              <Col span={6}>
                <Form.Item label='是否已读' name='isRead'>
                  <Select placeholder='请选择' options={enum2options(MyExportStatus)} />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Space>
                  <Button type='primary' htmlType='submit' loading={list.loading}>筛选</Button>
                  <Button htmlType='reset'>重置</Button>
                </Space>
              </Col>
            </Row>
          </Form>
        </div>
      </div>
      <div className="card content-card">
        <Table<MyExport>
          rowKey='id'
          loading={list.loading}
          dataSource={list.data?.data}
          columns={columns}
          scroll={{y: 700, x: 'max-content'}}
          pagination={{
            ...PAGINATION_CONFIG,
            current: searchParams.pageNum,
            pageSize: searchParams.pageSize,
            total: list.data?.totalCount || 0,
            onChange: (page, pageSize) => {
              setSearchParams({
                ...searchParams,
                pageNum: page === searchParams.pageNum ? 1 : page,
                pageSize,
              })
            }
          }}
        />
      </div>
    </div>
  );
};

export default AppUserPage;
